
$(function(){
    class views {
        constructor() {
            this.router = new router()
            this.init()
        }
        init() {
            $('.app').html('')
        }
    }
    class page1 extends views{
        constructor() {
            super();
            this.render()
        }
        render() {
            $('.app').append(`<div class="page1">
                我是page1
            </div>`)
            $('.page1').on('click',()=>{
                this.router.push('page2',{name:'page2'})
            })
        }
    }
    class page2 extends views {
        constructor() {
            super();
            this.render()
        }
        render () {
            $('.app').append(`<div class="page2">
                <button class="back">返回</button>
                我是page2
            </div>`)
            $('.back').on('click',()=>{
                this.router.back()
            })
        }
    }
    class index extends views{
        constructor() {
            super();
            this.render()
        }
        render() {
            this.router.replace('index',{})
            $('.app').append(`<div class="test">我是index</div>`)
            $('.test').on('click',()=> {
                this.router.push('page1',{name:'1111'})
            })
        }
    }
    var routerInfo = [
        {
            path:'page1',
            component() {
                new page1()
            }
        },
        {
            path:'index',
            component() {
                new index()
            }
        },
        {
            path:'page2',
            component() {
                new page2()
            }
        }
    ]
    function router() {

    }
    router.prototype= {
        push(path,query){
            routerInfo.forEach((v)=>{
                    if (v.path == path) {
                        v.component()
                        const state = {path,query};
                        history.pushState(state,'1',path)
                    }
            })
        },
        replace(path,query) {
            const state = {path,query}
            history.replaceState(state,'2',path)
        },
        go(n) {
            history.go(n)
        },
        back() {
            history.back()
        }
    }
    
    var demo = {
        init() {
            new index()
            window.addEventListener('popstate',function(e){
                routerInfo.forEach((v)=>{
                    if (v.path == e.state.path) {
                        v.component()
                    }
                })
            })
        }
    }
    demo.init()
})
